package services

import (
	"encoding/json"
	"errors"
	"fmt"
	"go.uber.org/zap"
	"io/ioutil"
	"net/http"
	"purchase-mall/utils"
)

type TokenInfoResp struct {
	Status       int             `json:"status"`
	Message      string          `json:"message"`
	ResponseJson []*ResponseJson `json:"responseJson"`
}

type ResponseJson struct {
	Account           string `json:"account"`
	NickName          string `json:"nickName"`
	TrafficLevel      string `json:"trafficLevel"`
	TrafficStartTime  string `json:"trafficStartTime"`  // 限额开始执行时间
	TrafficExpiretime string `json:"trafficExpiretime"` //限额有效期
	Traffic           struct {
		Quota int64 `json:"quota"` //用户可请求总量
		Qps   int64 `json:"qps"`   //用户qps限制
	} `json:"traffic"`
}

func GetTokenInfo(token string) (infos *TokenInfoResp, err error) {
	url := utils.TokenInfoUrl
	url = fmt.Sprintf("%s%s%s", url, "token[]=", token)

	client := &http.Client{}
	request, err := http.NewRequest("GET", url, nil)
	request.Header.Add("authorization", "name=kFpx3kId;client=aSZON9SFyar2")

	resp, err := client.Do(request)
	if err != nil {
		zap.L().Error("tokenInfo Http Api failed",
			zap.String("token", token),
			zap.Error(err))
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal(body, &infos)
	if err != nil {
		zap.L().Error("json Unmarshal failed",
			zap.String("token", token),
			zap.Error(err))
		return nil, err
	}

	if infos.Status != 200 {
		return nil, errors.New("status error")
	}
	if infos.Message != "查询成功" {
		return nil, errors.New("message error")
	}

	return
}
